#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/9/7 11:45 
# @Author : Hankin
# @File : updateVideo.py
# @desc :

import requests
import pymysql
import config
import os
import oss2
import time
def mysql_conn():
    conn = pymysql.connect(host=config.mysql_config['host'], user=config.mysql_config['user'], password=config.mysql_config['password'], database=config.mysql_config['db'])
    cur = conn.cursor()
    return conn,cur

def mysql_close(conn, cur):
    cur.close()
    conn.close()
def download_pic(url):
    if ("local-pictures.oss-cn-shenzhen.aliyuncs.com" in url or "images.ufutx.com" in url):
        return url
    response = requests.get(url)
    content = response.content
    path_dir = 'imgs'
    if not os.path.exists(path_dir):
        os.mkdir(path_dir)
    file_name = url.split('?')[0].rsplit('/', 1)[1]
    file_path = os.path.join(path_dir,file_name)
    if os.path.isfile(file_path):
        oss_url = upload_file(file_path)
        return oss_url
    with open(file_path , 'wb') as f:
        f.write(content)
    oss_url = upload_file(file_path)
    return oss_url

def upload_file(file):
    # 阿里云配置
    ALIOSS_ID = config.ALIOSS_ID
    ALIOSS_SECRET = config.ALIOSS_SECRET
    ALIOSS_Endpoint = config.ALIOSS_Endpoint
    ALIOSS_BUCKET = config.ALIOSS_BUCKET
    ALIOSS_HOST = config.ALIOSS_HOST
    auth = oss2.Auth(ALIOSS_ID, ALIOSS_SECRET)
    bucket = oss2.Bucket(auth, ALIOSS_Endpoint, ALIOSS_BUCKET)

    path = time.strftime("%Y%m", time.localtime())
    day = time.strftime("%d", time.localtime())
    print(file)
    file_name = file.rsplit('\\', 1)[1]
    object = path + "/" + day + "/" + file_name
    result = bucket.put_object_from_file(object, file)
    file_url = ALIOSS_HOST + '/' + object
    return file_url

def main():
    conn,cur = mysql_conn()
    sql = "select * from ufutx_anchor_videos where video_url is null"
    cur.execute(sql)
    rows = cur.fetchall()
    for row in rows:
        cover = row[6]
        url = download_pic(cover)
        video_url = upload_file(row[9])
        try:
            update_sql = f"update ufutx_anchor_videos set cover = '{url}' , video_url = '{video_url}' where cover = {cover}"
            print(sql)
            cur.execute(update_sql)
            conn.commit()
        except Exception as err:
            conn.rollback()
            print(err)

    mysql_close(conn, cur)
if __name__ == "__main__":
    main()